using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using ObjectLibrary;

namespace _0912089_0912172
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    /// 

    public class MenuScreen : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private Plane[] wallPlane;
        GraphicsDeviceManager graphics;
        const int MAX_PLAYER_PER_TEAM = 8;
        string[] COMPUTER_NAME = { "JACK", "MARKY", "DEEDEE", "JOEY", "OGGY", "KILLER", "SINBAD", "BRUCE", "CHEATER", "HUNTER", "CODER", "ABOSS", "NINJA", "BATMAN", "NERD", "SNIPER", "SPY" };
        string[] MAP_NAME = { "map01", "map02"};
        //string[] TIME_COMBO_BOX = { };
        int[] TIME_COMBO_BOX = {120,180,300,600,900,30 };
        int[] POINT_COMBO_BOX = {15,30,50,100,5 };
        int limitTimeIndex = 0;
        int limitPointIndex = 0;
        private int playerTeam = 0;
        private int mapIndex = 0;
        int WallIndex;
        MyCamera camera;
        MotionCamera motionCamera;
        NormalPerspectiveCamera normalCamera;
        BasicEffect effect;
        int height;
        int width;
        My3DModel theWalls;
        private MyCursor cursor;
        private SpriteBatch spriteBatch;
        List<Vector3> listPostion;
        List<Vector3> listTarget;
        List<Vector3> listUpVector;
        List<int> listCamera;
        bool isDraggedLeftMouse = false;

        List<string> AngleForceName;
        List<string> DemonForceName;
        List<TextField> DemonForce;
        List<TextField> AngleForce;

        List<FormItem> listFormItem;

        private MyButton exitBtn;
        private MyButton multiPlayBtn;
        private MyButton optionBtn;
        private MyButton singlePlayBtn;
        private MyButton trainBtn;

        private MyButton startGameBtn;
        private MyButton startSelectBtn;
        private MyButton mainMenuFromSelectBtn;
        private MyButton gameOptionBtn;
        private MyCombobox selectNumberOfComputerPlayer;
        private TextField forceABtn;
        private TextField forceDBtn;
        private MyCombobox mapSelect;
        private MyCombobox limitTimeSelect;
        private MyCombobox limitPointSelect;

        private List<MyButton> characterSelect;

        private MyButton mainMenuBtn;

        private TextField optionName;
        private MyCheckBox optionMusic;
        private MyCheckBox optionFullScreen;
        private MyCombobox optionResolution;
        private MyCombobox optionLevel;
        private MyValueBar optionVolume;

        private MyCombobox activeComboBox;
        private TextField activeTextField;

        My3DModel skyDom;

        public MenuScreen(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
            height = game.Window.ClientBounds.Height;
            width = game.Window.ClientBounds.Width;
            graphics = ((Game1)game).Graphics;
            Initialize();

        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here

            base.Initialize();
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            cursor = new MyCursor(Game.Content);

            string[] numberPlayerStrings = new string[2 * MAX_PLAYER_PER_TEAM - 1];
            for (int i = 0; i < numberPlayerStrings.Length; i++)
            {
                numberPlayerStrings[i] = (i + 1).ToString("00");
            }
            if (Global.gameSetting.Music)
            {
                MediaPlayer.Play(Global.backgroundMusic);
            }
            skyDom = new My3DModel(Game.Content, @"Resources/Map/Map01/Sky", 100, new Vector3(0, -60, 60), 0);
            theWalls = new My3DModel(Game.Content, @"Resources/Menu/Wall/wall", 10, Vector3.Zero, 0);
            //theWalls = new My3DModel(Game.Content, @"Resources/tank", 0.01f, Vector3.Zero, 0);

            wallPlane = new Plane[]{ new Plane(new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 0, 0)), 
                                  new Plane(new Vector3(-11.67f, 0, 0), new Vector3(-11.67f, 1, 0), new Vector3(-11.67f, 0, 1)), 
                                  new Plane(new Vector3(11.67f, 0, 0), new Vector3(11.67f, 1, 0), new Vector3(11.67f, 0, 1)) };

            listPostion = new List<Vector3>();
            listTarget = new List<Vector3>();
            listUpVector = new List<Vector3>();

            listPostion.Add(new Vector3(-0.5f, 5, 10));
            listTarget.Add(new Vector3(-0.5f, 5, 0));
            listUpVector.Add(new Vector3(0, 1, 0));

            listPostion.Add(new Vector3(0.0f, 5.0f, 7.5f));
            listTarget.Add(new Vector3(-11.6f, 5.0f, 7.5f));
            listUpVector.Add(new Vector3(0, 1, 0));

            listPostion.Add(new Vector3(1.6f, 4.5f, 8));
            listTarget.Add(new Vector3(11.6f, 4.5f, 8));
            listUpVector.Add(new Vector3(0, 1, 0));

            listPostion.Add(new Vector3(1.6f, 5.5f, 16));
            listTarget.Add(new Vector3(11.6f, 5.5f, 16));
            listUpVector.Add(new Vector3(0, 1, 0));

            listPostion.Add(new Vector3(-2.8f, 15, 20));
            listTarget.Add(new Vector3(2.0f, 4, 0));
            listUpVector.Add(new Vector3(0, 1, 0));

            listCamera = new List<int>();

            motionCamera = new MotionCamera();

            motionCamera.initCamera(
                new Vector3(0, 30f, 30f),
                new Vector3(0, 0, 0),
                new Vector3(0, 1, 0),
                1f,
                400,
                MathHelper.PiOver4,
                width / height);

            camera = motionCamera;

            int index = 0;
            WallIndex = 0;
            motionCamera.setNewInfor(listPostion[index], listTarget[index], listUpVector[index], 100);

            normalCamera = new NormalPerspectiveCamera();
            normalCamera.initCamera(
                new Vector3(0, 8f, 25f),
                new Vector3(0, 2, 0),
                new Vector3(0, 1, 0),
                1f,
                50,
                MathHelper.PiOver4,
                width / height);
            effect = new BasicEffect(GraphicsDevice);

            VisibleGameEntity3D.SetContent(Game.Content);
            VisibleGameEntity3D.SetGraphicsDevice(Game.GraphicsDevice);
            /***********************************************/
            singlePlayBtn = new MyButton(@"Resources/Menu/SinglePlay", 0.7f, new Vector3(-1.4f, 6f, 0.1f), 0);
            multiPlayBtn = new MyButton(@"Resources/Menu/MutiPlay", 0.7f, new Vector3(-1.5f, 5f, 0.1f), 0);
            trainBtn = new MyButton(@"Resources/Menu/Train", 0.7f, new Vector3(-1.3f, 4f, 0.1f), 0);
            optionBtn = new MyButton(@"Resources/Menu/Option", 0.7f, new Vector3(-1.0f, 3f, 0.1f), 0);
            exitBtn = new MyButton(@"Resources/Menu/Exit", 0.7f, new Vector3(3f, 2f, 0.1f), 0);


            //******************************************************/
            string[] timeList = new string[TIME_COMBO_BOX.Length];
            for (int i = 0; i < timeList.Length; i++)
            {
                timeList[i] = (TIME_COMBO_BOX[i] / 60).ToString("00") + ":" + (TIME_COMBO_BOX[i] % 60).ToString("00");
            }
            string[] listPoint = new string[POINT_COMBO_BOX.Length];
            for (int i = 0; i < listPoint.Length; i++)
            {
                listPoint[i] = POINT_COMBO_BOX[i].ToString();
            }
            limitPointSelect = new MyCombobox(listPoint, 0.3f, new Vector3(11.66f, 6f, 9f), -MathHelper.PiOver2);
            limitTimeSelect = new MyCombobox(timeList, 0.3f, new Vector3(11.66f, 5f, 9f), -MathHelper.PiOver2);
            mapSelect = new MyCombobox(new string[] { "Map 01", "Map 02" }, 0.3f, new Vector3(11.66f, 7f, 9f), -MathHelper.PiOver2);
            characterSelect = new List<MyButton>();
            characterSelect.Add(new MyButton(@"Resources/Menu/ChooseFighter/random", 0.2f, new Vector3(11.65f, 2.5f, 13.5f), -MathHelper.PiOver2));
            characterSelect.Add(new MyButton(@"Resources/Menu/ChooseFighter/cat", 0.2f, new Vector3(11.65f, 2.5f, 14.5f), -MathHelper.PiOver2));
            characterSelect.Add(new MyButton(@"Resources/Menu/ChooseFighter/bear", 0.2f, new Vector3(11.65f, 2.5f, 15.5f), -MathHelper.PiOver2));

            startGameBtn = new MyButton(@"Resources/Menu/Start", 0.7f, new Vector3(11.65f, 2.2f, 19.5f), -MathHelper.PiOver2);
            gameOptionBtn = new MyButton(@"Resources/Menu/GameOption", 0.7f, new Vector3(11.65f, 3.2f, 19f), -MathHelper.PiOver2);

            selectNumberOfComputerPlayer = new MyCombobox(numberPlayerStrings, 0.2f, new Vector3(11.66f, 9.3f, 15.3f), -MathHelper.PiOver2);


            forceABtn = new TextField("Angle Force", 0.3f, new Vector3(11.66f, 8.2f, 14f), -MathHelper.PiOver2);
            forceDBtn = new TextField("Demon Force", 0.3f, new Vector3(11.66f, 8.2f, 18f), -MathHelper.PiOver2);

            forceABtn.Color = new Vector4(0.8f, 0.8f, 0.8f, 1);
            forceDBtn.Color = new Vector4(0.5f, 0.5f, 0.5f, 1);

            mainMenuFromSelectBtn = new MyButton(@"Resources/Menu/MainMenu", 0.7f, new Vector3(11.65f, 2.5f, 6.5f), -MathHelper.PiOver2);
            startSelectBtn = new MyButton(@"Resources/Menu/Start", 0.7f, new Vector3(11.65f, 1.5f, 8f), -MathHelper.PiOver2);
            /************************************************/
            mainMenuBtn = new MyButton(@"Resources/Menu/MainMenu", 0.7f, new Vector3(-11.64f, 1.0f, 3.5f), MathHelper.PiOver2);

            optionName = new TextField("PLAYER    ", 0.25f, new Vector3(-11.65f, 8.4f, 6f),
                            MathHelper.PiOver2);
            optionName.Position = optionName.Position - new Vector3(0, 0, optionName.Size.X / 2);
            optionMusic = new MyCheckBox(" ", 0.25f, new Vector3(-11.65f, 3.4f, 6f), MathHelper.PiOver2);
            optionMusic.Position = optionMusic.Position - new Vector3(0, 0, optionMusic.Size.X / 2);

            optionFullScreen = new MyCheckBox(" ", 0.25f, new Vector3(-11.65f, 5.9f, 6f), MathHelper.PiOver2);
            optionFullScreen.Position = optionFullScreen.Position - new Vector3(0, 0, optionFullScreen.Size.X / 2);

            optionResolution = new MyCombobox(new string[] { "800 x 600 ", "1024 x 768" }, 0.25f, new Vector3(-11.65f, 5.1f, 6f),
                            MathHelper.PiOver2);
            optionResolution.Position = optionResolution.Position - new Vector3(0, 0, optionResolution.Size.X / 2);

            optionLevel = new MyCombobox(new string[] { "Noob  ", "Pro   ", "Master" }, 0.25f, new Vector3(-11.65f, 7.6f, 6f),
                            MathHelper.PiOver2);

            optionLevel.Position = optionLevel.Position - new Vector3(0, 0, optionLevel.Size.X / 2);

            optionVolume = new MyValueBar(0.3f, new Vector3(-11.65f, 2.6f, 6f), MathHelper.PiOver2);
            optionVolume.Position = optionVolume.Position - new Vector3(0, 0, optionVolume.Size.X / 2);

            /****************/
            listFormItem = new List<FormItem>();


            listFormItem.Add(new MyPanel(new Vector2(350, 120), Color.FromNonPremultiplied(0, 0, 0, 128)
                , 1, new Vector3(-11.66f, 8.25f, 2.9f), MathHelper.PiOver2));

            listFormItem.Add(new MyPanel(new Vector2(350, 120), Color.FromNonPremultiplied(0, 0, 0, 128)
                , 1, new Vector3(-11.66f, 5.75f, 2.9f), MathHelper.PiOver2));

            listFormItem.Add(new MyPanel(new Vector2(350, 120), Color.FromNonPremultiplied(0, 0, 0, 128)
                , 1, new Vector3(-11.66f, 3.25f, 2.9f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("Game", 0.4f, new Vector3(-11.65f, 9f, 3f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("player name", 0.25f, new Vector3(-11.65f, 8.4f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("computer level", 0.25f, new Vector3(-11.65f, 7.6f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("Display", 0.4f, new Vector3(-11.65f, 6.5f, 3f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("full screen", 0.25f, new Vector3(-11.65f, 5.9f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("resolution", 0.25f, new Vector3(-11.65f, 5.1f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("Sound", 0.4f, new Vector3(-11.65f, 4f, 3f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("music", 0.25f, new Vector3(-11.65f, 3.4f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("volume", 0.25f, new Vector3(-11.65f, 2.6f, 6.2f), MathHelper.PiOver2));

            listFormItem.Add(new TextField("Computer player", 0.2f, new Vector3(11.66f, 9.3f, 15f), -MathHelper.PiOver2));

            listFormItem.Add(new TextField("Game Mode", 0.3f, new Vector3(11.66f, 8f, 7f), -MathHelper.PiOver2));
            listFormItem.Add(new TextField("Map", 0.3f, new Vector3(11.66f, 7f, 7f), -MathHelper.PiOver2));
            listFormItem.Add(new TextField("Limit Point", 0.3f, new Vector3(11.66f, 6f, 7f), -MathHelper.PiOver2));
            listFormItem.Add(new TextField("Limit Time", 0.3f, new Vector3(11.66f, 5f, 7f), -MathHelper.PiOver2));

            foreach (FormItem item in listFormItem)
            {
                item.Enable = false;
                if (item.RotationY == MathHelper.PiOver2)
                    item.Position = item.Position + new Vector3(0, 0, item.Size.X / 2);
                else if (item.RotationY == 3 * MathHelper.PiOver2)
                {
                    item.Position = item.Position - new Vector3(0, 0, item.Size.X / 2);
                }
            }

            listFormItem.Add(new MyPanel(new Vector2(80, 80), Color.FromNonPremultiplied(255, 255, 255, 255)
                , 35, 1, new Vector3(11.66f, 2.5f, 13.5f), -MathHelper.PiOver2));
            listFormItem.Add(new MyPanel(new Vector2(80, 80), Color.FromNonPremultiplied(255, 255, 255, 255)
                , 35, 1, new Vector3(11.66f, 2.5f, 14.5f), -MathHelper.PiOver2));
            listFormItem.Add(new MyPanel(new Vector2(80, 80), Color.FromNonPremultiplied(255, 255, 255, 255)
                , 35, 1, new Vector3(11.66f, 2.5f, 15.5f), -MathHelper.PiOver2));
            listFormItem.Add(singlePlayBtn);
            listFormItem.Add(multiPlayBtn);
            listFormItem.Add(trainBtn);
            listFormItem.Add(optionBtn);
            listFormItem.Add(exitBtn);

            listFormItem.Add(mainMenuBtn);
            listFormItem.Add(optionFullScreen);
            listFormItem.Add(optionLevel);
            listFormItem.Add(optionMusic);
            listFormItem.Add(optionName);
            listFormItem.Add(optionResolution);
            listFormItem.Add(optionVolume);

            listFormItem.Add(mainMenuFromSelectBtn);
            listFormItem.Add(startSelectBtn);
            listFormItem.Add(startGameBtn);
            listFormItem.Add(gameOptionBtn);

            listFormItem.Add(forceABtn);
            listFormItem.Add(forceDBtn);
            listFormItem.Add(selectNumberOfComputerPlayer);

            listFormItem.Add(mapSelect);
            listFormItem.Add(limitPointSelect);
            listFormItem.Add(limitTimeSelect);

            AngleForceName = new List<string>();
            DemonForceName = new List<string>();
            AngleForce = new List<TextField>();
            DemonForce = new List<TextField>();
            for (int i = 0; i < MAX_PLAYER_PER_TEAM; i++)
            {
                AngleForce.Add(new TextField("-", 0.25f, new Vector3(11.66f, 7.5f - i * 0.5f, 14f), -MathHelper.PiOver2));
                DemonForce.Add(new TextField("-", 0.25f, new Vector3(11.66f, 7.5f - i * 0.5f, 18f), -MathHelper.PiOver2));
            }



            loadSetting();
        }

        private void loadSetting()
        {
            GameSetting setting = Global.gameSetting;
            optionName.setString(setting.PlayerName, false);
            optionLevel.SetItemAt(setting.ComputerLevel);
            optionFullScreen.IsChecked = setting.IsFullScreen;
            if (setting.Resolusion == new Vector2(800, 600))
            {
                optionResolution.SetItemAt(0);
            }
            else if (setting.Resolusion == new Vector2(1024, 768))
            {
                optionResolution.SetItemAt(1);
            }
            optionVolume.Value = setting.Volume;
            optionMusic.IsChecked = setting.Music;

        }

        private void setResolution(int index)
        {
            Vector2 resolution = new Vector2(800, 600);
            switch (index)
            {
                case 1:
                    resolution = new Vector2(1024, 768);
                    break;
            }
            graphics.PreferredBackBufferWidth = (int)resolution.X;
            graphics.PreferredBackBufferHeight = (int)resolution.Y;
            //graphics.PreferMultiSampling = false;
            //graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            Global.gameSetting.Resolusion = resolution;
        }

        private void setForce()
        {
            int i = 0;
            foreach (string name in AngleForceName)
            {
                AngleForce[i].setString(name, true);
                AngleForce[i].Color = new Vector4(0.9f, 0.9f, 0.9f, 1);
                i++;
            }
            if (playerTeam == 0)
            {
                AngleForce[i].setString(Global.gameSetting.PlayerName, true);
                AngleForce[i].Color = new Vector4(1, 0.5f, 0.5f, 1);
                i++;
            }
            while (i < AngleForce.Count)
            {
                AngleForce[i].setString("-", true);
                AngleForce[i].Color = new Vector4(0.8f, 0.8f, 0.8f, 1);
                i++;
            }
            i = 0;
            foreach (string name in DemonForceName)
            {
                DemonForce[i].setString(name, true);
                DemonForce[i].Color = new Vector4(0.9f, 0.9f, 0.9f, 1);
                i++;
            }
            if (playerTeam == 1)
            {
                DemonForce[i].setString(Global.gameSetting.PlayerName, true);
                DemonForce[i].Color = new Vector4(1, 0.5f, 0.5f, 1);
                i++;
            }
            while (i < DemonForce.Count)
            {
                DemonForce[i].setString("-", true);
                DemonForce[i].Color = new Vector4(0.8f, 0.8f, 0.8f, 1);
                i++;
            }
        }
        Random random = new Random(System.DateTime.Now.Millisecond);
        public void addAComputer()
        {

            string name = COMPUTER_NAME[random.Next(COMPUTER_NAME.Length)];
            if (AngleForceName.Count > DemonForceName.Count)
            {
                DemonForceName.Add(name);
            }
            else if (AngleForceName.Count < DemonForceName.Count)
            {
                AngleForceName.Add(name);
            }
            else if (playerTeam == 1)
            {
                AngleForceName.Add(name);
            }
            else
            {
                DemonForceName.Add(name);
            }
        }
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 
        double t = 0;
        bool isEscapeKeyPressed = false;
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here

            base.Update(gameTime);
            Random r = new Random();

            HandleMouseInput();



            camera.Update(gameTime);
            if (motionCamera.isSettled())
            {
                if (listCamera.Count > 0)
                {
                    int index = listCamera[0];
                    motionCamera.setNewInfor(listPostion[index], listTarget[index], listUpVector[index], 20);
                    listCamera.RemoveAt(0);
                }
            }
            foreach (MyButton btn in characterSelect)
            {
                btn.Update(gameTime);
            }
            foreach (FormItem item in listFormItem)
            {
                item.Update(gameTime);
            }

            ///==================================================>
            #region Handle KeyBoard Input
            KeyboardState kbs = Keyboard.GetState();
            if (activeTextField != null)
            {
                if (!activeTextField.KeyHandle(kbs))
                {
                    activeTextField.IsEditting = false;
                    if (activeTextField == optionName)
                    {
                        Global.gameSetting.PlayerName = optionName.getString();
                    }
                    activeTextField = null;

                }
                return;
            }

            if (kbs.IsKeyDown(Keys.Escape))
            {
                isEscapeKeyPressed = true;
            }
            if (kbs.IsKeyUp(Keys.Escape) && isEscapeKeyPressed)
            {
                /*
                Game.Components.Clear();
                //Game.Components.RemoveAt(0);
                Global.gameMode = Global.GAME_MODE.PLAYING;
                    PlayingScreen playScreen = new PlayingScreen(Game);

                    Game.Components.Add(playScreen);
                    playScreen.addPlayer(1, 0,"C1", false,0);
                    playScreen.addPlayer(1, 0,Global.gameSetting.PlayerName, true,0);
                    playScreen.addPlayer(1, 0,"C2", false,0);
                    playScreen.addPlayer(0, 0,"C3", false,1);
                    playScreen.addPlayer(0, 0,"C4", false,1);
                    playScreen.StartGame();
                 * */
            }
            #endregion
            ///==================================================>
        }

        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(new Color(0.0f, 0.0f, 0.2f));

            GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
            skyDom.DrawWithFog(gameTime, GraphicsDevice, null, camera, 300, 305);

            GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

            theWalls.Draw(gameTime, GraphicsDevice, effect, camera);
            foreach (TextField text in AngleForce)
            {
                text.Draw(gameTime, GraphicsDevice, effect, camera);
            }
            foreach (TextField text in DemonForce)
            {
                text.Draw(gameTime, GraphicsDevice, effect, camera);
            }
            foreach (FormItem item in listFormItem)
            {
                item.Draw(gameTime, GraphicsDevice, effect, camera);
            }
            foreach (MyButton btn in characterSelect)
            {
                btn.Draw(gameTime, GraphicsDevice, effect, camera);
            }

            spriteBatch.Begin();
            cursor.Draw(gameTime, spriteBatch);
            spriteBatch.End();

            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            base.Draw(gameTime);
        }

        public Ray CalculateCursorRay(Matrix projectionMatrix, Matrix viewMatrix)
        {
            int x = Mouse.GetState().X;
            int y = Mouse.GetState().Y;
            

            Vector3 nearSource = new Vector3(x, y, 0f);
            Vector3 farSource = new Vector3(x, y, 1f);

            Vector3 nearPoint = GraphicsDevice.Viewport.Unproject(nearSource,
                projectionMatrix, viewMatrix, Matrix.Identity);

            Vector3 farPoint = GraphicsDevice.Viewport.Unproject(farSource,
                projectionMatrix, viewMatrix, Matrix.Identity);

            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();

            return new Ray(nearPoint, direction);
        }
        private void chooseCharacter(int index)
        {
            for (int i = 0; i < characterSelect.Count; i++)
            {
                if (i == index)
                {
                    characterSelect[i].DefaultLight = 1f;
                    characterSelect[i].Enable = false;
                }
                else
                {
                    characterSelect[i].DefaultLight = 0.8f;
                    characterSelect[i].Enable = true;
                }
            }
        }
        private void HandleMouseInput()
        {
            MouseState ms = Mouse.GetState();
            cursor.Position = new Vector2(ms.X, ms.Y);
            if (listCamera.Count > 0 || !motionCamera.isSettled())
                return;

           
            Ray cursorRay = CalculateCursorRay(camera.Projection, camera.View);
            float? distance = cursorRay.Intersects(wallPlane[WallIndex]);
            if (!distance.HasValue)
                return;
            Vector3 contactPoint = cursorRay.Position + cursorRay.Direction * distance.Value;

            foreach (FormItem item in listFormItem)
            {
                if ((WallIndex == 0 && item.RotationY == 0)
                    || (WallIndex == 1 && item.RotationY == MathHelper.PiOver2)
                    || (WallIndex == 2 && item.RotationY == 3 * MathHelper.PiOver2)
                    )
                {
                    item.IsChosen = item.isClicked(contactPoint);
                }
                else
                    item.IsChosen = false;
            }
            if (WallIndex == 2)
            {
                foreach (MyButton btn in characterSelect)
                {
                    btn.IsChosen = btn.isClicked(contactPoint);
                }
            }
            if (activeComboBox != null)
            {
                int index = activeComboBox.GetItemAt(contactPoint);

                activeComboBox.ItemSelectedIndex = index;


            }
            if (ms.LeftButton == ButtonState.Pressed)
            {
                if (isDraggedLeftMouse == false) // Bat dau an trai chuot
                {
                    isDraggedLeftMouse = true;
                }
                if (optionVolume.IsChosen)
                {
                    optionVolume.Adjust(contactPoint);
                    MediaPlayer.Volume = optionVolume.Value / 100f;

                    Global.gameSetting.Volume = optionVolume.Value;
                }
            }
            if (ms.LeftButton == ButtonState.Released)
            {
                if (isDraggedLeftMouse == true) // Bat dau tha trai chuot ra
                {
                    isDraggedLeftMouse = false;

                    if (activeComboBox != null)
                    {
                        int index = activeComboBox.GetItemAt(contactPoint);
                        if (index != -1)
                        {
                            activeComboBox.SetItemAt(index);
                            if (activeComboBox == selectNumberOfComputerPlayer)
                            {
                                AngleForceName.Clear();
                                DemonForceName.Clear();
                                for (int i = 0; i <= index; i++)
                                {
                                    addAComputer();
                                }
                                setForce();
                            }
                            else if (activeComboBox == optionLevel)
                            {
                                Global.gameSetting.ComputerLevel = index;
                            }
                            else if (activeComboBox == optionResolution)
                            {
                                setResolution(index);
                            }
                            else if (activeComboBox == mapSelect)
                            {
                                mapIndex = index;
                            }
                            else if (activeComboBox == limitTimeSelect)
                            {
                                limitTimeIndex = index;
                            }
                            else if (activeComboBox == limitPointSelect)
                            {
                                limitPointIndex = index;
                            }
                        }
                        activeComboBox.IsExplained = false;
                        activeComboBox = null;
                        return;
                    }
                    if (activeTextField != null)
                    {
                        activeTextField.IsEditting = false;
                        if (activeTextField == optionName)
                        {
                            Global.gameSetting.PlayerName = optionName.getString();
                        }
                        activeTextField = null;
                        return;
                    }
                    /**************************/


                    if (singlePlayBtn.IsChosen)
                    {
                        int index = 2;
                        WallIndex = 2;
                        listCamera.Add(4);
                        listCamera.Add(index);

                        AngleForceName.Clear();
                        DemonForceName.Clear();
                        selectNumberOfComputerPlayer.SetItemAt(0);
                        addAComputer();
                        setForce();
                        chooseCharacter(0);
                    }
                    else if (multiPlayBtn.isClicked(contactPoint))
                    {

                    }
                    else if (trainBtn.IsChosen)
                    {
                        Game.Components.Clear();
                        Global.gameMode = Global.GAME_MODE.PLAYING;
                        PlayingScreen playScreen = new PlayingScreen(Game);

                        Game.Components.Add(playScreen);
                        playScreen.addPlayer(0, 0, Global.gameSetting.PlayerName, true, 0);
                        playScreen.StartGame();
                    }
                    else if (optionBtn.IsChosen)
                    {
                        int index = 1;
                        WallIndex = 1;
                        listCamera.Add(4);
                        listCamera.Add(index);

                    }
                    else if (exitBtn.IsChosen)
                    {
                        Game.Exit();
                    }

                    /*********************/
                    for (int i = 0; i < characterSelect.Count; i++)
                    {

                        if (characterSelect[i].IsChosen)
                        {
                            chooseCharacter(i);
                        }

                    }
                    if (startGameBtn.IsChosen)
                    {
                        Game.Components.Clear();
                        //Game.Components.RemoveAt(0);
                        MediaPlayer.Stop();
                        Global.gameMode = Global.GAME_MODE.PLAYING;
                        PlayingScreen playScreen = new PlayingScreen(Game);

                        Game.Components.Add(playScreen);
                        playScreen.initMap(MAP_NAME[mapIndex]);
                        for (int i = 0; i < AngleForceName.Count; i++)
                        {
                            playScreen.addPlayer(0, 0,AngleForceName[i], false,Global.gameSetting.ComputerLevel);
                        }
                        for (int i = 0; i < DemonForceName.Count; i++)
                        {
                            playScreen.addPlayer(1,  0,DemonForceName[i], false, Global.gameSetting.ComputerLevel);
                        }
                        playScreen.addPlayer(playerTeam, 0,Global.gameSetting.PlayerName, true,0);
                        playScreen.VictoryPoint = POINT_COMBO_BOX[limitPointIndex];
                        playScreen.LimitSecondGameTime = TIME_COMBO_BOX[limitTimeIndex];
                        playScreen.StartGame();
                       
                    }
                    else if (gameOptionBtn.IsChosen)
                    {
                        int index = 2;
                        WallIndex = 2;
                        listCamera.Add(index);
                    }
                    else if (selectNumberOfComputerPlayer.IsChosen)
                    {
                        selectNumberOfComputerPlayer.IsExplained = !selectNumberOfComputerPlayer.IsExplained;
                        activeComboBox = selectNumberOfComputerPlayer;
                    }
                    else if (forceABtn.IsChosen && playerTeam != 0)
                    {
                        if (DemonForceName.Count < AngleForceName.Count)
                        {
                            string temp = AngleForceName.Last();
                            DemonForceName.Add(temp);
                            AngleForceName.Remove(temp);
                        }
                        playerTeam = 0;
                        setForce();
                    }
                    else if (forceDBtn.IsChosen && playerTeam != 1)
                    {
                        if (DemonForceName.Count > AngleForceName.Count)
                        {
                            string temp = DemonForceName.Last();
                            AngleForceName.Add(temp);
                            DemonForceName.Remove(temp);
                        }
                        playerTeam = 1;
                        setForce();
                    }
                    else if (startSelectBtn.IsChosen)
                    {
                        int index = 3;
                        WallIndex = 2;
                        listCamera.Add(index);

                    }
                    else if (mapSelect.IsChosen)
                    {
                        activeComboBox = mapSelect;
                        mapSelect.IsExplained = true;
                    }
                    else if (limitPointSelect.IsChosen)
                    {
                        activeComboBox = limitPointSelect;
                        limitPointSelect.IsExplained = true;
                    }
                    else if (limitTimeSelect.IsChosen)
                    {
                        activeComboBox = limitTimeSelect;
                        limitTimeSelect.IsExplained = true;
                    }
                    /*********************/
                    if (mainMenuBtn.IsChosen || mainMenuFromSelectBtn.IsChosen)
                    {
                        int index = 0;
                        WallIndex = 0;
                        listCamera.Add(4);
                        listCamera.Add(index);
                    }
                    else if (optionMusic.IsChosen)
                    {
                        optionMusic.IsChecked = !optionMusic.IsChecked;
                        if (optionMusic.IsChecked)
                        {
                            MediaPlayer.Play(Global.backgroundMusic);
                        }
                        else
                        {
                            MediaPlayer.Stop();
                        }
                        Global.gameSetting.Music = optionMusic.IsChecked;
                    }
                    else if (optionFullScreen.IsChosen)
                    {
                        optionFullScreen.IsChecked = !optionFullScreen.IsChecked;
                        //graphics.PreferMultiSampling = optionFullScreen.IsChecked;
                        graphics.IsFullScreen = optionFullScreen.IsChecked;
                        graphics.ApplyChanges();
                        Global.gameSetting.IsFullScreen = optionFullScreen.IsChecked;

                    }
                    else if (optionResolution.IsChosen)
                    {
                        optionResolution.IsExplained = !optionResolution.IsExplained;
                        activeComboBox = optionResolution;
                    }
                    else if (optionLevel.IsChosen)
                    {
                        optionLevel.IsExplained = !optionLevel.IsExplained;
                        activeComboBox = optionLevel;
                    }
                    else if (optionName.IsChosen)
                    {
                        optionName.IsEditting = !optionName.IsEditting;
                        activeTextField = optionName;
                    }

                }
            }



            if (ms.MiddleButton == ButtonState.Pressed)
            {

                camera = normalCamera;

                int x = ms.X - GraphicsDevice.Viewport.Width / 2;
                int y = ms.Y - GraphicsDevice.Viewport.Height / 2;

                if (x != 0)
                {
                    ((NormalPerspectiveCamera)camera).RotationY -= x * Global.mouseSpeed;
                    camera.UpdateCameraInfo();
                }
                Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
            }
            else
            {
                camera = motionCamera;

            }
        }
    }
}
